<div class="{{$viewClass['form-group']}}">

    <label class="{{$viewClass['label']}} control-label">{{$label}}</label>

    <div class="{{$viewClass['field']}}">

        @include('admin::form.error')

        <div {!! $attributes !!} style="width: 100%; height: 100%;border:1px solid #ccc;z-index: {{$zIndex}} ">
            <div class="toolbar-container"><!-- 工具栏 --></div>
            <div class="editor-container" style="height: {{$height}}px;"><!-- 编辑器 --></div>
        </div>

        <input type="hidden" name="{{$name}}" value="{{ old($column, $value) }}"/>

        @include('admin::form.help-block')

    </div>
</div>

<!-- script标签加上 "init" 属性后会自动使用 Dcat.init() 方法动态监听元素生成 -->
<script init="{!! $selector !!}">
    var { createEditor, createToolbar } = window.wangEditor;
    var editorConfig = {
        placeholder: "{{$placeholder}}",
        MENU_CONF: {},
        onChange(editor) {
            let html = editor.getHtml();
            $("#"+id).parent().find('input[type="hidden"]').val(html);
        }
    };
    var editor;
    //本地上传 目前仅支持图片
    @if(config('filesystems.default') == 'public')
        editorConfig.MENU_CONF['uploadImage'] = {
        server: '/editor/wang/image',
        fieldName:'file',
        maxFileSize: 200 * 1024 * 1024
    }
    editorConfig.MENU_CONF['uploadVideo'] = {
        server: '/editor/wang/video',
        fieldName:'file',
        maxFileSize: 200 * 1024 * 1024
    }
    @endif
    //七牛云
    @if(config('filesystems.default') == 'qiniu')
    function showFullUrl(url){
        return window.location.protocol+'//'+"{{config('filesystems.disks.qiniu.domain')}}"+'/'+url;
    }
    editorConfig.MENU_CONF['uploadImage'] = {
        async customUpload(file, insertFn) {
            let observable = qiniu.upload(file, null, "{{$uptoken}}", {}, {
                region: {{$config['region']}},
                upprotocol: "{{request()->isSecure()?'https':'http'}}",
                chunkSize: 1
            });
            observable.subscribe({
                next: (res) => {
                    editor.showProgressBar(Math.floor(res.total.percent));
                },
                error: (res) => {
                },
                complete: (res) => {
                    insertFn(showFullUrl(res.data.id));
                }
            });
        }
    };
    editorConfig.MENU_CONF['uploadVideo'] = {
        async customUpload(file, insertFn) {
            let observable = qiniu.upload(file, null, "{{$uptoken}}", {}, {
                region: {{$config['region']}},
                upprotocol: "{{request()->isSecure()?'https':'http'}}",
                chunkSize: 1
            });
            observable.subscribe({
                next: (res) => {
                    editor.showProgressBar(Math.floor(res.total.percent));
                },
                error: (res) => {
                    console.log(res);
                },
                complete: (res) => {
                    insertFn(showFullUrl(res.data.id));
                }
            });
        }
    };
    @endif
    //阿里云oss
    @if(config('filesystems.default') == 'oss')
    /**
     * 生成唯一文件名
     * @param {Number} len 生成的文件名长度
     * @param {Number} radix 指定基数
     */
    function getuuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
        var uuid = []
        var i = 0
        radix = radix || chars.length

        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
        } else {
            var r
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
            uuid[14] = '4'

            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16
                    uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
                }
            }
        }

        return uuid.join('')
    }
    /**
     * 生成唯一文件名 时间戳 + 随机数
     * @param {Number} len 生成的文件名长度
     * @param {Number} radix 指定基数
     */
    function getTimeId(len, radix) {
        if (len) {
            const time = new Date().getTime()
            const uuid = getuuid(len, radix)
            return `${time}${uuid}`
        } else {
            console.log('请输入长度')
        }
    }
    function showFullUrl(url){
        return window.location.protocol+'//'+"{{config('filesystems.disks.oss.bucket')}}"+'.'+"{{config('filesystems.disks.oss.endpoint')}}"+'/'+url;
    }
    var oss_client = new OSS({
        region: "{{$region}}",
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: "{{config('filesystems.disks.oss.access_key')}}",
        accessKeySecret: "{{config('filesystems.disks.oss.secret_key')}}",
        // 从STS服务获取的安全令牌（SecurityToken）。
        // 填写Bucket名称，例如examplebucket。
        bucket: "{{config('filesystems.disks.oss.bucket')}}",
    });
    editorConfig.MENU_CONF['uploadImage'] = {
        async customUpload(file, insertFn) {
            let dir = "{{config('admin.upload.directory.image')}}";
            let filename = getTimeId(8,12);
            let fileext = file.name.substring(file.name.lastIndexOf('.') + 1);
            let alt = file.name;
            oss_client.put(
                `${dir}/${filename}.${fileext}`,
                file
            ).then(res=>{
                insertFn(res.url, alt, res.url)
            }).catch(err=>{
                console.log(err);
            });
        }
    };
    editorConfig.MENU_CONF['uploadVideo'] = {
        async customUpload(file, insertFn) {
            let dir = "{{config('admin.upload.directory.file')}}";
            let filename = getTimeId(8,12);
            let fileext = file.name.substring(file.name.lastIndexOf('.') + 1);
            oss_client.multipartUpload(`${dir}/${filename}.${fileext}`,file,{
                progress:(p,cpt,res)=>{
                    editor.showProgressBar(Math.floor(p*100));
                },
                parallel: 3,
                partSize: 1024 * 1024,
            }).then(res=>{
                insertFn(showFullUrl(res.name))
            }).catch(err=>{
                console.log(err);
            });

        }
    };
    @endif

        editor = createEditor({
        selector: '#'+id+' .editor-container',
        html: $("#"+id).parent().find('input[type="hidden"]').val(),
        config: editorConfig,
        mode: 'default', // or 'simple'
    });
    var toolbarConfig = {};
    toolbarConfig.excludeKeys = [
        'fullScreen',
    ];
    var toolbar = createToolbar({
        editor,
        selector: '#'+id+' .toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    });
</script>
